package com.example.mynote.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mynote.R;
import com.example.mynote.base.BaseActivity;
import com.example.mynote.entity.Note;

import org.litepal.LitePal;

import java.util.List;

public class EditNoteActivity extends BaseActivity {
    private android.widget.ImageButton editCancel;
    private android.widget.TextView editTitle;
    private android.widget.ImageButton editSave;
    private android.widget.EditText editCTitle;
    private android.widget.EditText editContent;

    @Override
    protected int initLayout() {
        return R.layout.activity_edit_note;
    }

    @Override
    protected void initView() {

        editCancel = (ImageButton) findViewById(R.id.edit_cancel);
        editTitle = (TextView) findViewById(R.id.edit_title);
        editSave = (ImageButton) findViewById(R.id.edit_save);
        editCTitle = (EditText) findViewById(R.id.edit_c_title);
        editContent = (EditText) findViewById(R.id.edit_content);
    }

    @Override
    protected void initData() {
        editCancel.setOnClickListener(v -> {
            Toast.makeText(this, "已取消修改", Toast.LENGTH_SHORT).show();
            onBackPressed();
        });
        if (getIntent() != null) {
            int id = getIntent().getIntExtra("id", 0);
            List<Note> all = LitePal.findAll(Note.class, id);
            editTitle.setText("编辑日记");
            editCTitle.setText(all.get(0).getTitle());
            editContent.setText(all.get(0).getContent());
            editSave.setOnClickListener(v -> {
                String title = editCTitle.getText().toString();
                String content = editContent.getText().toString();
                if (!title.equals("") && !content.equals(all.get(0).getContent())) {
                    ContentValues values = new ContentValues();
                    values.put("content", content);
                    LitePal.updateAll(Note.class, values, "content = ? and time = ?", all.get(0).getContent(), all.get(0).getTime() + "");
                    Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    Toast.makeText(this, "请先编辑内容", Toast.LENGTH_SHORT).show();
                }
            });
        }


    }
}